package com.yqg.protection.netty;

import com.yqg.protection.netty.encode.factory.ProtocolDiscriminatorFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

@Component
@Slf4j
public class NettyServer {

    private final ProtocolDiscriminatorFactory discriminatorFactory;

    @Autowired
    public NettyServer(ProtocolDiscriminatorFactory discriminatorFactory) {
        this.discriminatorFactory = discriminatorFactory;
        log.info("Netty服务器实例已创建");
    }

    public void startServer(int port) throws Exception {
        log.info("正在启动Netty服务器，端口: {}", port);

        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            log.info("初始化新连接: {}", ch.remoteAddress());

                            // 添加日志处理器
                            ch.pipeline().addLast("logger", new LoggingHandler("NETTY", LogLevel.DEBUG));

                            // 为每个连接创建新的协议识别器实例
                            ch.pipeline().addLast("protocolDiscriminator",
                                    discriminatorFactory.create());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("服务器启动成功，监听端口: {}", port);
            future.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            log.info("服务器已关闭");
        }
    }
}
